package com.shanlitech.bluetooth;

import android.graphics.Color;
import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.shanlitech.bluetooth.sample.SampleDatabase;
import com.shanlitech.bluetooth.sample.SampleRecorder;
import com.shanlitech.bluetooth.map.Map2D;
import com.shanlitech.bluetooth.map.MapMarker;
import com.shanlitech.lbs.sample.OneshotSample;
import com.shanlitech.lbs.geometry.Point2D;
import com.shanlitech.lbs.geometry.Round2D;
import com.shanlitech.lbs.locator.LocateContext;
import com.shanlitech.lbs.locator.RssOneShootLocator;
import com.shanlitech.lbs.map.LbsDatabase;
import com.shanlitech.lbs.types.AccelerationRecord;
import com.shanlitech.lbs.types.RssiRecord;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link OneShotFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class OneShotFragment extends Fragment {
    private static final String TAG = "SLBluetooth";

    private class SampleAdapter extends BaseAdapter {
        private class Holder {
            public TextView name;
            public Button btnTest;
        }

        private final SampleDatabase database;

        public SampleAdapter(SampleDatabase database) {
            this.database = database;
        }

        @Override
        public int getCount() {
            return database.getOneshot().size();
        }

        @Override
        public Object getItem(int i) {
            return database.getOneshot(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup viewGroup) {
            LayoutInflater inflater = LayoutInflater.from(getContext());
            Holder holder;
            if( convertView == null ) {
                convertView = inflater.inflate(R.layout.sample_item,null);
                holder = new Holder();
                holder.name = convertView.findViewById(R.id.sample_file);
                holder.btnTest = convertView.findViewById(R.id.btn_test);
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
                holder.name = convertView.findViewById(R.id.sample_file);
                holder.btnTest = convertView.findViewById(R.id.btn_test);
            }

            final OneshotSample sample = database.getOneshot(i);
            if(sample != null) {
                String name = sample.getName();
                holder.name.setText(name);
                holder.name.setOnClickListener(v -> {
                    showSampleLocation(i);
                });
                holder.btnTest.setOnClickListener(v -> {
                    testSample(i);
                });
            } else {
                Log.d(TAG,"can not found sample at " + i);
            }
            return convertView;
        }
    }

    private Map2D mMap;
    private Button mTestAll;
    private Button mSaveSample;
    private Button mOneShot;
    private BluetoothScanner mScanner;
    private AccelerationSensor mAcceleration;
    private SampleRecorder mRecorder;
    private MapMarker mMarker;
    private SampleAdapter mAdapter;


    public OneShotFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public static OneShotFragment newInstance() {
        return new OneShotFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_one_shot, container, false);
        mMap = view.findViewById(R.id.map);
        mTestAll = view.findViewById(R.id.button_test_all_sample);
        mSaveSample = view.findViewById(R.id.button_save_oneshot);
        mOneShot = view.findViewById(R.id.button_oneshot);
        mScanner = new BluetoothScanner(getContext());

        mAcceleration = new AccelerationSensor(getContext());
        mRecorder = new SampleRecorder(getContext());

        mAdapter = new SampleAdapter( SampleDatabase.getInstance(getContext()));
        ListView lv = view.findViewById(R.id.list_oneshot);
        lv.setAdapter(mAdapter);
        /*
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int idx, long id) {
                showSampleLocation(idx);
            }
        });
         */

        mSaveSample.setEnabled(false);

        mTestAll.setOnClickListener(v -> {
            testAllSample();
        });

        mSaveSample.setOnClickListener(v -> {
            saveAsSample();
        });

        mOneShot.setOnClickListener(v -> {
            startOneShot();
        });

        MapMarker.Builder builder = new MapMarker.Builder(this.getContext(),"marker");
        mMarker = builder.loadImage("res://com.shanlitech.bluetooth:drawable/marker")
                .setAnchor(MapMarker.ANCHOR_BOTTOM_MIDDLE)
                .setDrawSize(80,80)
                .setDraggable(true)
                .setTextMode(MapMarker.TEXT_COORDINATE)
                .setTextSize(20.f)
                .setTextColor(Color.BLUE)
                .setCoordinate(AppContext.getLocation())
                .build();
        mMap.addStaticMarker(mMarker);
        mMap.initialize(false,MapMarker.TEXT_NAME);
        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
        mScanner.stop();
        mTestAll.setEnabled(true);
        mSaveSample.setEnabled(false);
        mOneShot.setEnabled(true);
    }

    private void startOneShot() {
        mSaveSample.setEnabled(false);
        mTestAll.setEnabled(false);
        if( mScanner.isStart() ) {
            return;
        }
        mScanner.start(this::onScan, AppContext.getFlat().getBeacons().keySet(), 3000);
        mAcceleration.start();
        mOneShot.setEnabled(false);
    }

    private void showSampleLocation(int idx) {
        if( mScanner.isStart() ) {
            return;
        }
        final OneshotSample sample = SampleDatabase.getInstance(getContext()).getOneshot(idx);
        if( sample == null ) {
            return;
        }
        mMarker.setCoordinate(sample.location);
        mMap.invalidate();
    }

    private void testSample(int idx) {
        if( mScanner.isStart() ) {
            return;
        }
        final OneshotSample sample = SampleDatabase.getInstance(getContext()).getOneshot(idx);
        if( sample == null ) {
            return;
        }
        final LocateContext lc = RssOneShootLocator.locateDetail(LbsDatabase.getInstance(),sample.rssiRecords);
        if( lc != null ) {
            mMap.clearDynamic();
            showLocateResult(lc,true,true);
            mMap.addDynamicPoint(sample.location,Color.BLUE);
            mMap.invalidate();
        }
    }
    private void testAllSample() {
        if( mScanner.isStart() ) {
            return;
        }

        final List<Double> diffs = new ArrayList<>();
        double d_sum = 0;
        double d_max = 0;
        double d_min = Double.MAX_VALUE;
        mMap.clearDynamic();
        for(OneshotSample sample : SampleDatabase.getInstance(getContext()).getOneshot()) {
            final LocateContext lc = RssOneShootLocator.locateDetail(LbsDatabase.getInstance(),sample.rssiRecords);
            if( lc != null ) {
                mMap.addDynamicLine(sample.location, lc.getLocation(), Color.DKGRAY);
                mMap.addDynamicPoint(sample.location, Color.BLUE);
                mMap.addDynamicPoint(lc.getLocation(), Color.RED);
                final double d = Point2D.distance(sample.location,lc.getLocation());
                if( d > d_max ) {
                    d_max = d;
                }
                if( d < d_min ) {
                    d_min = d;
                }
                d_sum += d;
                diffs.add(d);
            }
        }
        mMap.invalidate();

        if( !diffs.isEmpty() ) {
            final double mean = d_sum / diffs.size();
            d_sum = 0;
            for(double d : diffs) {
                d_sum += Math.pow(d - mean,2);
            }
            final double stddev = Math.sqrt(d_sum / diffs.size());
            final String msg = String.format(Locale.getDefault(),
                    "%d samples\nmean=%.2f\nmax=%.2f\nmin=%.2f\nstddev=%.2f",
                    diffs.size(),mean,d_max,d_min,stddev
                    );
            AlertDialog dialog = new AlertDialog.Builder(getContext())
                    .setMessage(msg)
                    .setPositiveButton(R.string.ok, (dia,which) -> {
                        dia.dismiss();
                    }).create();
            dialog.show();
        }
    }

    private void saveAsSample() {
        final Point2D location = mMarker.getCoordinate();
        final Point2D lastLocation = AppContext.getLocation();
        if( Point2D.distance(location,lastLocation) > 5.0 ) {
            AlertDialog dialog = new AlertDialog.Builder(getContext())
                    .setMessage(R.string.save_sample_distance_warn)
                    //设置对话框的按钮
                    .setNegativeButton(R.string.cancel, (d,which) -> {
                        d.dismiss();
                    })
                    .setPositiveButton(R.string.save, (d,which) -> {
                        d.dismiss();
                        mRecorder.saveAsOneshot(AppContext.getFlat(), location);
                        mRecorder.clear();
                        AppContext.setLocation(location);
                        mAdapter.notifyDataSetInvalidated();
                        mSaveSample.setEnabled(false);
                    }).create();
            dialog.show();
        } else {
            mRecorder.saveAsOneshot(AppContext.getFlat(),location);
            mRecorder.clear();
            AppContext.setLocation(location);
            mAdapter.notifyDataSetInvalidated();
            mSaveSample.setEnabled(false);
        }
    }

    private void onScan(List<RssiRecord> signals) {
        final List<AccelerationRecord> accRecords = mAcceleration.getReset();
        mScanner.stop();
        mAcceleration.stop();
        mRecorder.clear();
        mRecorder.addRssi(signals);
        mRecorder.addAcc(accRecords);

        mOneShot.setEnabled(true);
        mTestAll.setEnabled(true);

        final LocateContext lc = RssOneShootLocator.locateDetail(LbsDatabase.getInstance(),signals);
        if( lc != null ) {
            mSaveSample.setEnabled(true);
            AppContext.setLocation(lc.getLocation());

            showLocateResult(lc,true,true);
            if( Point2D.distance(mMarker.getCoordinate(),lc.getLocation()) > 5.0 ) {
                mMarker.setCoordinate(lc.getLocation());
            }
            mMap.invalidate();
        }
    }

    private void showLocateResult(LocateContext lc,boolean showRound,boolean showProcess) {
        mMap.clearDynamic();
        if( showRound ) {
            for (Round2D r : lc.getRounds()) {
                mMap.addDynamicRound(r, Color.GREEN);
            }
        }
        if( showProcess ) {
            for (Point2D point : lc.getProcess()) {
                mMap.addDynamicPoint(point, Color.DKGRAY);
            }
        }
        mMap.addDynamicPoint(lc.getLocation(),Color.RED); // 最终位置
    }
}